package com.zhouzj.task.springcloud.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.zhouzj.task.springcloud.gateway.feign.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * @Author: zhouzhijun
 * @Date: 2021/8/6 10:39
 */
@Component
public class SSOFilter implements GlobalFilter, Ordered {

    @Autowired
    private UserService userService;

    private static final List<String> includes = Arrays.asList("/info/");

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        if (includes.stream().noneMatch(include -> StrUtil.contains(path, include))) {
            return chain.filter(exchange);
        }

        String token = request.getHeaders().getFirst("token");
        String email = userService.info(token);
        if (StrUtil.isBlank(email)) {
            // 拒绝访问，状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            String data = "UNAUTHORIZED!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }

        // 合法请求，放行，执行后续的过滤器
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
